<?php
include("account.php");

function GetNewUserId() {
  $account_id = apc_fetch('user_new_account_id');
  if (!$account_id) {
    $sql=sprintf("SELECT MAX(id) AS maxid FROM password");
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);
    if ($row) {
      apc_add('user_new_account_id', $row['maxid'] + 1, 3600 * 2);
      $account_id = $row['maxid'] + 1;
    } else {
      $account_id = 0;
    }
  } else {
    apc_inc('user_new_account_id');
  }
  return $account_id;
}

$user_id = GetLoginId($_COOKIE['t']);

if ($user_id && $user_id > 0) {
  $res_word = "{'code':300, 'desc':'用户已经登录'}";
  header('Location: ' . $URL_MY_PAGE);
} else {
  $user_email = $_POST['email'];
  $user_nick = $_POST['nick'];
  if (!$user_nick) {
    $user_nick = $user_email;
  }
  $user_pwd = $_POST['uk'];

  $conn = mysql_connect("127.0.0.1","root","");
  mysql_select_db("user_account");

  $sql=sprintf("SELECT id FROM password WHERE email='%s'", mysql_real_escape_string($user_email));
  $result = mysql_query($sql);
  $row = mysql_fetch_array($result);

  if ($row) {
    $res_word = "{'code':400, 'desc':'用户" . $user_email . "已经存在'}";
  } else {
    $pwd_hash = GetPasswordHash($user_pwd);
    $user_id = GetNewUserId();
    $sql = sprintf("INSERT INTO password(id, email, nick, password) VALUES (%s, '%s', '%s', '%s')", $user_id, 
        mysql_real_escape_string($user_email), mysql_real_escape_string($user_nick), $pwd_hash);
    $res = mysql_query($sql);
    if ($res) {
      $res_word = "{'code':0, 'desc':'新用户注册成功'}";
    } else {
      $res_word = "{'code':500, 'desc':'新用户注册失败，请稍后重试。'}";
    }
  }
  mysql_close($conn);
}
?>
<?php
echo $res_word;
?>

